package com.example.logindb.controller;

import com.example.logindb.dto.UserDTO;
import com.example.logindb.entity.Location;
import com.example.logindb.entity.Route;
import com.example.logindb.entity.User;
import com.example.logindb.sevices.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
public class AdminController {

    private UserService userService;
    private RouteService routeService;
    private RelationService relationService;
    private OnlineService onlineService;
    private LocationService locationService;
    @Autowired
    public AdminController(UserService userService, RouteService routeService, RelationService relationService, OnlineService onlineService, LocationService locationService) {
        this.userService = userService;

        this.routeService = routeService;
        this.relationService = relationService;
        this.onlineService = onlineService;
        this.locationService = locationService;
    }

    @GetMapping("/dashboard")
    public String adminHome(Principal principal,Model model) {

        List<UserDTO> users = userService.findAllByRole("USER");
        User user =userService.findByUsername(principal.getName());

        model.addAttribute("users", users);
        model.addAttribute("name", user.getName());

        return "Admin/AdminHomePage";
    }

    @GetMapping("/loc")
    public String adminLocation(Principal principal,Model model) {

        List<UserDTO> users = userService.findAllByRole("USER");
        User user =userService.findByUsername(principal.getName());

        model.addAttribute("users", users);
        model.addAttribute("name", user.getName());

        return "Info/LocationInfo";
    }



    @PostMapping("/dashboard/delete")
    public String removeUser(@RequestParam int id) {

        userService.deleteUserById(id);
        return "redirect:/dashboard";
    }

    @GetMapping("/dashboard/updateUser")
    public String showUpdateForm(@RequestParam int id , Model model) {
        UserDTO userDTO= userService.findById(id);
        model.addAttribute("user",userDTO);
        return "Admin/UpdateUser";
    }

    @PostMapping("/dashboard/updateUser/save")
    public String updateUser(@ModelAttribute("user") UserDTO userDTO) {
        userService.updateUser(userDTO);
        return "redirect:/dashboard";
    }

    @GetMapping("/dashboard/search")
    public String searchUser(@RequestParam String name ,Principal principal , Model model) {
        List<UserDTO> users = userService.searchUser("USER",name);
        User user =userService.findByUsername(principal.getName());
        model.addAttribute("users",users);
        model.addAttribute("name", user.getName());
        return "Info/UserInfo";
    }

    @GetMapping("/dashboard/search2")
    public String searchUser2(@RequestParam String name,
                             @RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "6") int size,
                             Model model) {
        Pageable pageable = PageRequest.of(page - 1, size); // Spring Data JPA 的分页参数从0开始
        Page<User> users = userService.searchUser2("USER", name, pageable);

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = userService.findByUsername(userDetails.getUsername());

        model.addAttribute("users", users.getContent());
        model.addAttribute("name1", name);
        model.addAttribute("totalPages", users.getTotalPages());
        model.addAttribute("totalElements", users.getTotalElements());
        model.addAttribute("presentPage", page);

        System.out.println("Total Pages: " + users.getTotalPages());
        System.out.println("Total Elements: " + users.getTotalElements());
//        System.out.println("Total Pages: " + users.getContent());
        return "Info/UserInfo";
    }

    @GetMapping("/dashboard/search3")
    public String searchUser3(@RequestParam String name,
                              Model model) {
        Pageable pageable = PageRequest.of(0, 3); // Spring Data JPA 的分页参数从0开始
        Page<User> users = userService.searchUser2("USER", name, pageable);

//        model.addAttribute("name", name);
        model.addAttribute("users", users);
//        model.addAttribute("name", name);
//        model.addAttribute("totalPages", users.getTotalPages());
//        model.addAttribute("totalElements", users.getTotalElements());
//        System.out.println("Total Pages: " + users.getTotalPages());
//        System.out.println("Total Elements: " + users.getTotalElements());
////        System.out.println("Total Pages: " + users.getContent());
      return "Info/UserInfo";
    }

//    @GetMapping("/dashboard/search3")
//    public String searchUser3(HttpServletRequest request, @RequestParam String username,@RequestParam(name = "pageNum", defaultValue = "1") int pageNum) {
//        PageInfo<User> pageInfo= userService.selectAll(username,pageNum, 2);
//        System.out.println("当前页：" + pageInfo.getPageNum());
//        System.out.println("每页显示的数量：" + pageInfo.getPageSize());
//        System.out.println("当前页的数量：" + pageInfo.getSize());
//        System.out.println("总记录数：" + pageInfo.getTotal());
//        System.out.println("总页数：" + pageInfo.getPages());
//        System.out.println("结果集:" + pageInfo.getList());
//        System.out.println("第一页:" + pageInfo.getNavigateFirstPage());
//        System.out.println("前一页:" + pageInfo.getPrePage());
//        System.out.println("下一页:" + pageInfo.getNextPage());
//        System.out.println("最后一页:" + pageInfo.getNavigateLastPage());
//        System.out.println("是否为第一页：" + pageInfo.isIsFirstPage());
//        System.out.println("是否为最后一页：" + pageInfo.isIsLastPage());
//        System.out.println("是否有前一页：" + pageInfo.isHasPreviousPage());
//        System.out.println("是否有下一页：" + pageInfo.isHasNextPage());
//        System.out.println("导航页码数" + pageInfo.getNavigatePages());
//        System.out.println("所有导航页号" + Arrays.toString(pageInfo.getNavigatepageNums()));
//        request.setAttribute("pageInfo", pageInfo);
//        return "Info/UserInfo";
//    }



    @GetMapping("/dashboard/showroutes")
    @ResponseBody // 这个注解非常重要，它告诉 Spring MVC 返回的是数据而非视图
    public String getRouteById(@RequestParam("id") int id) {
        List<Route> routes = routeService.findByBlindID(id);
        if (!routes.isEmpty()) {
            return routes.get(0).getGeojson(); // 假设你只返回一个 Route 对象
        }
        // 如果没有找到任何路线，你可以抛出异常或者返回 null
        return null;
    }
    //统计各角色人数
    @GetMapping("/dashboard/statis")
    @ResponseBody // 这个注解非常重要，它告诉 Spring MVC 返回的是数据而非视图
    public List<Integer> getStatisByRole() {
        List<Integer> sum = new java.util.ArrayList<>(List.of());
        sum.add(userService.countByUserrole("volunteer"));
        sum.add(userService.countByUserrole("blind"));
        sum.add(userService.countByUserrole("guardian"));
        return sum;
    }
    //绑定盲人数与未绑定数
    @GetMapping("/dashboard/blindnumber")
    @ResponseBody
    public List<Integer> bindBlind() {
        int b = userService.countByUserrole("blind");
        int r = relationService.count();
        List<Integer> sum = new java.util.ArrayList<>(List.of());
        sum.add(b-r);//未绑定
        sum.add(r);//绑定
        return sum;
    }
    //查询在线人数
    @GetMapping("/dashboard/onlinecount")
    @ResponseBody
    public Integer onlineCount() {

        return onlineService.getCountByStatus();

    }
    //获取所有在线点
    @GetMapping("/points")
    @ResponseBody
    public List<Map<String, Object>> getLocations() {
        return userService.getUserLocations();
    }

//    @GetMapping("/dashboard/sort")
//    public String SortUser(@RequestParam Model model) {
//        List<Map<String, Object>>blind =routeService.findTopThree();
//        List<Integer> blindids = new ArrayList<>();
//        for (Map<String, Object> entry : blind) {
//            // 从映射中获取 blindid 的值
//            Integer blindid = (Integer) entry.get("blindid");
//            blindids.add(blindid);
//        }
//        // 获取 blindid 的值
//        List<Integer> blindcounts = new ArrayList<>();
//        for (Map<String, Object> entry : blind) {
//            // 从映射中获取 blindid 的值
//            Integer blindcount = (Integer) entry.get("count");
//            blindcounts.add(blindcount);
//        }
//        // 根据 blindid 获取次数
//        List<User> blinds = userService.findUsersByBlindids(blindids);
//
//
//        model.addAttribute("blindcounts", blindcounts);
//        model.addAttribute("blinds", blinds);
//
//        return "Admin/AdminHomePage";
//    }


    @GetMapping("/dashboard/addUser")
    public String showRegistrationForm(Model model) {
        UserDTO user = new UserDTO();
        model.addAttribute("newUser",user);
        return "User/RegistrationPage";
    }

    @GetMapping("/dashboard/UserInfo")
    public String showUserInfo() {
        return "Info/UserInfo";
    }

    @GetMapping("/dashboard/editProfile")
    public String updateAdminForm(Principal principal, Model model) {

        User user =userService.findByUsername(principal.getName());
        model.addAttribute("user",user);
        return "Admin/UpdateUser";
    }


    @PostMapping("/dashboard/editProfile/save")
    public String updateAdmin(@ModelAttribute("user") UserDTO userDTO) {
        userService.updateUser(userDTO);
        return "redirect:/dashboard";
    }

//    @PostMapping("/upload")
//    public String uploadFile(@RequestParam("image") MultipartFile file,
//                             @RequestParam("id") String id){
//        try {
//            // 获取文件名
//            String fileName = file.getOriginalFilename();
//            // 指定保存路径
//            String uploadPath="";
//            String filePath = uploadPath + "/" + id + "/" + fileName;
//            // 保存文件到本地
//            file.transferTo(new File(filePath));
//            // 向 Python 发送处理请求
//            URL url = new URL("http://localhost:8090/" + id);
//            HttpURLConnection con = (HttpURLConnection) url.openConnection();
//            con.setRequestMethod("GET");
//
//            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
//            String inputLine;
//            StringBuffer content = new StringBuffer();
//            while ((inputLine = in.readLine()) != null) {
//                content.append(inputLine);
//            }
//            in.close();
//            con.disconnect();
//
//            System.out.println(content);
//
//            return content.toString();
//        } catch (IOException e) {
//            e.printStackTrace();
//            return "Fail";
//        }


}
